package listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @author Fairy
 */
public class OnLineCountListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("Session创建");
        ServletContext servletContext = se.getSession().getServletContext();
        Integer onlineCount = (Integer)servletContext.getAttribute("onlineCount");
        if (onlineCount == null) {
            onlineCount = 1;
        } else {
            onlineCount++;
        }
        servletContext.setAttribute("onlineCount", onlineCount);
        HttpSessionListener.super.sessionCreated(se);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("Session销毁");
        ServletContext servletContext = se.getSession().getServletContext();
        Integer onlineCount = (Integer)servletContext.getAttribute("onlineCount");
        onlineCount--;

        servletContext.setAttribute("onlineCount", onlineCount);
        HttpSessionListener.super.sessionDestroyed(se);
    }
}
